package com.music.checkpoints.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.music.checkpoints.common.config.dao.RedisConfiguration;
import com.music.checkpoints.common.convert.NationNoanswerTempory2TemporyQuestVO;
import com.music.checkpoints.common.core.page.Page;
import com.music.checkpoints.common.dao.*;
import com.music.checkpoints.common.entity.*;
import com.music.checkpoints.common.enums.ErrorCodeEnum;
import com.music.checkpoints.common.exception.ServiceException;
import com.music.checkpoints.common.service.CacheManager;
import com.music.checkpoints.common.service.MonitorManager;
import com.music.checkpoints.common.utils.DateUtil;
import com.music.checkpoints.common.vo.NoanswerTemporyVO;
import com.music.checkpoints.common.vo.ScoreVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MonitorManagerImpl implements MonitorManager {
    @Autowired
    private MonitorDao monitorDao;
    @Autowired
    private NationSignUpDao signUpDao;
    @Autowired
    private NationNoanswerTemporyDao noanswerTemporyDao;
    @Autowired
    private NationExamineeDao examineeDao;
    @Autowired
    private NationExamDetailDao detailDao;
    @Autowired
    private RedisConfiguration redisConfiguration;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public Map<String, Object> login(String idCard) {
        Monitor monitor = monitorDao.queryByIdCard(idCard);
        if (monitor == null) {
            throw new ServiceException(ErrorCodeEnum.E005.code(), ErrorCodeEnum.E005.getDescription());
        }
        NationSignUp nationSignUp = signUpDao.querySignUpByExamId(monitor.getExamId());
        if (nationSignUp == null) {
            throw new ServiceException(ErrorCodeEnum.E006.code(), ErrorCodeEnum.E006.getDescription());
        }
        //总考试人数
        Integer peoples = signUpDao.queryCountBySiteId(monitor.getExamId());

        String token = UUID.randomUUID().toString();
        this.generateToken(token);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("name", monitor.getName());
        map.put("head_img_url", monitor.getHeadImgUrl());
        map.put("site_name", nationSignUp.getExamSite());
        map.put("begin", DateUtil.toString(nationSignUp.getBeginTimeUnix().longValue(), "yyyy-MM-dd HH:mm:ss"));
        map.put("end", DateUtil.toString(nationSignUp.getEndTimeUnix().longValue(), "yyyy-MM-dd HH:mm:ss"));
        map.put("subject", nationSignUp.getSubject() == null ? "音乐基础" : nationSignUp.getSubject());
        map.put("level", nationSignUp.getLevel());
        map.put("peoples", peoples);
        map.put("site_id", nationSignUp.getExamId());

        return map;
    }

    @Override
    public void generateToken(String token) {
        StringBuilder sb = new StringBuilder();
        sb.append(redisConfiguration.getRedisPrefix());
        sb.append(redisConfiguration.getMonitorToken());
        sb.append(token);
        cacheManager.put(sb.toString(), token, redisConfiguration.getTokenExpire());
        return;
    }

    @Override
    public Page<NoanswerTemporyVO> questions(Integer siteId, Integer pageSize, Integer pageNum) {
        Integer curPage = (pageNum - 1) * pageSize;
        List<NationSignUp> signUpList = signUpDao.querySignUpPage(siteId, curPage, pageSize);
        Integer pageTotal = signUpDao.queryCountBySiteId(siteId);

        List<NoanswerTemporyVO> noanswerTemporyVOList = new ArrayList<>();
        if (signUpList.size() > 0) {
            for (NationSignUp signUp : signUpList) {
                NoanswerTemporyVO temporyVO = new NoanswerTemporyVO();
                NationExaminee nationExaminee = examineeDao.queryById(signUp.getUid());
                //考生信息
                if (nationExaminee != null) {
                    temporyVO.setHeadImgUrl(nationExaminee.getHeadUrl());
                    temporyVO.setName(nationExaminee.getRealname());
                    temporyVO.setSex(nationExaminee.getSex());
                    temporyVO.setIdCard(nationExaminee.getCardNum());
                }
                //报名信息
                temporyVO.setExamCode(signUp.getExamCode());
                temporyVO.setLevel(signUp.getLevel());
                temporyVO.setSubject(signUp.getSubject() == null ? "音乐基础" : signUp.getSubject());
                temporyVO.setUid(signUp.getUid());
                //答题信息
                List<NationNoanswerTempory> noanswerTemporyList = noanswerTemporyDao.queryNoanswerTempory(siteId, signUp.getUid());
                if (noanswerTemporyList.size() > 0) {
                    temporyVO.setQuestions(noanswerTemporyList.stream()
                            .map(e -> NationNoanswerTempory2TemporyQuestVO.convert(e))
                            .collect(Collectors.toList()));
                }
                //得分信息
                NationExamDetail examDetail = detailDao.queryByExamCode(signUp.getExamCode());
                if (null != examDetail) {
                    temporyVO.setEvaluate(examDetail.getEvaluation());
                    temporyVO.setComment(JSON.parseObject(examDetail.getComment()));
                    temporyVO.setMoScore(examDetail.getMoScore());
                    temporyVO.setShiScore(examDetail.getShiScore());
                }
                noanswerTemporyVOList.add(temporyVO);
            }
        }

        return new Page<>(pageNum, pageTotal.longValue(), pageSize, noanswerTemporyVOList);
    }

    @Override
    public void completeScore(ScoreVO scoreVO) {
        List<NationNoanswerTempory> temporyList = noanswerTemporyDao.queryNoanswerTempory(scoreVO.getSiteId(), scoreVO.getUid());
        if (temporyList.size() > 0) {
            for (NationNoanswerTempory tempory : temporyList) {
                tempory.setStatus(1);
                noanswerTemporyDao.updateTempory(tempory);
            }
        }
        NationExamDetail examDetail = detailDao.queryByExamCode(scoreVO.getExamCode());
        if (examDetail != null) {
            examDetail.setStatus(1);
            examDetail.setMoScore(scoreVO.getMoScore());
            examDetail.setShiScore(scoreVO.getShiScore());
            examDetail.setTotalScore(examDetail.getScore() + scoreVO.getMoScore() + scoreVO.getShiScore());
            examDetail.setEvaluation(scoreVO.getEvaluate());
            examDetail.setComment(scoreVO.getComment());
            detailDao.updateExamDetail(examDetail);
        }
        return;
    }

    @Override
    public void missingExam(String examCode) {
        List<NationNoanswerTempory> temporyList = noanswerTemporyDao.queryNoanswerByExamCode(examCode);
        if (temporyList.size() == 0) {
            throw new ServiceException(ErrorCodeEnum.E007.code(), ErrorCodeEnum.E007.getDescription());
        }
        for (NationNoanswerTempory tempory : temporyList) {
            //缺考状态
            tempory.setStatus(2);
            noanswerTemporyDao.updateTempory(tempory);
        }
        return;
    }

    @Override
    public void missingCancel(String examCode) {
        List<NationNoanswerTempory> temporyList = noanswerTemporyDao.queryNoanswerByExamCode(examCode);
        if (temporyList.size() == 0) {
            throw new ServiceException(ErrorCodeEnum.E007.code(), ErrorCodeEnum.E007.getDescription());
        }
        for (NationNoanswerTempory tempory : temporyList) {
            //取消缺考状态
            tempory.setStatus(0);
            noanswerTemporyDao.updateTempory(tempory);
        }
        return;
    }
}
